package ai.fabu.dataplatform.service.GRPCServer;

import ai.fabu.dataplatform.CompatDeprecationServiceGrpc;
import ai.fabu.dataplatform.GetGroupRequest;
import ai.fabu.dataplatform.GetGroupResponse;
import ai.fabu.dataplatform.Index;
import ai.fabu.dataplatform.bean.util.IndexData;
import ai.fabu.dataplatform.constant.ResultCode;
import ai.fabu.dataplatform.help.Result;
import ai.fabu.dataplatform.service.ApiForDeprecationService;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.springboot.autoconfigure.grpc.server.GrpcService;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
public class DataPlatformCompatDeprecationServer {
    @GrpcService(CompatDeprecationServiceGrpc.class)
    private static class DataPlatformCompatDeprecationImpl extends CompatDeprecationServiceGrpc.CompatDeprecationServiceImplBase{
        @Autowired
        ApiForDeprecationService apiForDeprecationService;

        @Override
        public void getGroupByBag(GetGroupRequest request, StreamObserver<GetGroupResponse> responseObserver) {
            Result<IndexData> result;
            try{
                result = apiForDeprecationService.getGroupNameByBagName(request.getBagName());
            }
            catch (Exception e){
                FunctionUtil.errorHandler(responseObserver, "getGroupByBag", ResultCode.SYSTEM_ERROR.getMsg());
                throw e;
            }
            if(result.getCode() == ResultCode.SUCCESS.getCode()){
                IndexData data = result.getData();
                Index index = Index.newBuilder().setGroupName(data.getGroupName()).setBagName(data.getBagName()).build();
                GetGroupResponse response = GetGroupResponse.newBuilder().setIndex(index).build();
                responseObserver.onNext(response);
                responseObserver.onCompleted();
            }
            else{
                FunctionUtil.errorHandler(result, responseObserver, "getGroupByBag");
            }
        }
    }
}
